package com.jawmask.android.discover.bean.task;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;

import com.jawmask.android.discover.R;

@SuppressLint("NewApi")
public abstract class BaseDiscoverTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

	private final Context context;
	protected final int DEFAULT_BUFFER_SIZE = 1024 * 4;

	public BaseDiscoverTask(final Context context) {
		this.context = context;
	}

	protected String getGoogleAppKey() {
		return context.getString(R.string.google_api_key);
	}

	protected Context getContext() {
		return context;
	}

	protected Result doInBackground(Params... searchRequest) {
		try {
			String httpResponse = getHttpResponse(getRequestURI(searchRequest));
			return getObjectFromJSON(new JSONObject(httpResponse));
		} catch (URISyntaxException e) {

		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		} catch (JSONException e) {

		}
		return null;
	}

	protected String getHttpResponse(final URI httpUrl) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(httpUrl);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		String httpResponseStr = EntityUtils.toString(httpResponse.getEntity());
		httpClient.getConnectionManager().shutdown();
		return httpResponseStr;
	}

	protected abstract URI getRequestURI(final Params... parameter) throws URISyntaxException;

	protected abstract Result getObjectFromJSON(final JSONObject searchResultsJson) throws JSONException;
}
